package com.yilin.tms.truck.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yilin.commons.util.ArrayUtil;
import com.yilin.commons.util.StringUtil;
import com.yilin.tms.core.application.AppUtil;
import com.yilin.tms.core.application.PageData;
import com.yilin.tms.core.commons.utils.ParamUtil;
import com.yilin.tms.core.entity.order.party.OrderAppraise;

import com.yilin.tms.core.entity.truck.TruckSource;
import com.yilin.tms.core.entity.truck.TruckVehicle;
import com.yilin.tms.core.entity.user.UserType;
import com.yilin.tms.core.entity.user.account.Account;
import com.yilin.tms.core.entity.user.organize.Organize;
import com.yilin.tms.core.remote.IOrderRemote;
import com.yilin.tms.core.remote.IUserRemote;
import com.yilin.tms.truck.mapper.TruckSourceMapper;
import com.yilin.tms.truck.mapper.TruckVehicleMapper;
import com.yilin.tms.truck.service.ITruckSourceService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.transaction.Transactional;
import java.util.*;


/**
 * 车源服务
 */
@Service
@Transactional
public class TruckSourceService extends ServiceImpl<TruckSourceMapper, TruckSource> implements ITruckSourceService {

    @Resource
    TruckSourceMapper truckSourceMapper;
    @Resource
    TruckVehicleMapper vehicleMapper;

    @Resource
    IOrderRemote orderRemote;
    @Resource
    IUserRemote userRemote;


    /**
     * 获取车源分页
     * 按距离排序时传入position即可，无需传入sort
     */
    @Override
    public PageData<TruckSource> getTruckSourcePage(Account loginUser, TruckSource query, Integer page, Integer limit) {
        List<Integer> statuses = new ArrayList<>();
        if (query.getQueryStatuses() != null && query.getQueryStatuses().length > 0) {
            List<TruckSource.SourceStatus> statusList = Arrays.asList(query.getQueryStatuses());
            statuses = ArrayUtil.fieldAdd(statusList, obj -> obj.index);
        }
        PageData<TruckSource> pageQuery = new PageData<>(page, limit);
        if (StringUtil.isNotEmpty(query.getPosition())) pageQuery.addOrder(OrderItem.asc("distances"));
        PageData<TruckSource> pageData = truckSourceMapper.getTruckSourcePage(pageQuery, loginUser, query,statuses);
        if (ArrayUtil.isNotEmpty(pageData.getList())) {
            for (TruckSource truckSource : pageData.getList()) {
                //车辆详情链接
                truckSource.setVehicleDetailUrl(getVehicleDetailUrl(truckSource.getId()));
                ownerOptSet(truckSource,loginUser);
            }
        }
        return pageData;
    }

    /**
     * 获取车源详情
     */
    @Override
    public TruckSource getTruckSourceDetail(Account loginUser, String truckSourceId) {
        TruckSource truckSource = truckSourceMapper.selectById(truckSourceId);
        if (truckSource == null) return null;
        TruckVehicle vehicle = vehicleMapper.selectById(truckSource.getVehicleId());
        truckSource.setVehicle (vehicle);
        //车辆组织
        Organize organize = ParamUtil.isSuccess(userRemote.getOrganizeById(truckSource.getOrganizeId()));
        truckSource.setOrganize(organize);
        //获取该组织下前十条最近评价
        List<OrderAppraise> appraiseList = ParamUtil.isSuccess(orderRemote.getTopTenAppraiseList(truckSource.getOrganizeId()));
        truckSource.setAppraiseList(appraiseList);
        //车辆详情链接
        truckSource.setVehicleDetailUrl(getVehicleDetailUrl(truckSource.getId()));
        ownerOptSet(truckSource,loginUser);
        return truckSource;
    }

    /**
     * 获取车源分页 隐藏敏感信息
     * 按距离排序时传入position即可，无需传入sort
     */
    @Override
    public PageData<TruckSource> getPublicTruckSourcePage(TruckSource query, Integer page, Integer limit) {
        PageData<TruckSource> pageData = getTruckSourcePage(new Account(), query, page, limit);
        if (ArrayUtil.isNotEmpty(pageData.getList())) {
            pageData.getList().forEach(vehicle -> {
                vehicle.setVehicleDetailUrl(getVehicleDetailUrl(vehicle.getId()));
                if (StringUtil.isNotEmpty(vehicle.getOrganizeName())) {
                    vehicle.setOrganizeName(StringUtil.privateName(vehicle.getOrganizeName()));
                }
                if (StringUtil.isNotEmpty(vehicle.getTrackNo())) {
                    vehicle.setTrackNo(StringUtil.privateTrackNo(vehicle.getTrackNo()));
                }
            });
        }
        return pageData;
    }

    @Override
    public void saveTruckSource(Account loginUser, TruckSource param,String[] vehicleIds) {
        Organize organize = ParamUtil.isSuccess(userRemote.getOrganizeById(loginUser.getOrganizeId()));
        HashSet<String> setList = new HashSet<>(ArrayUtil.initList(vehicleIds));
        for (String vehicleId : setList) {
            TruckVehicle vehicle = vehicleMapper.selectById(vehicleId);
            if (!vehicle.getOrganizeId().equals(loginUser.getOrganizeId())) continue;
            TruckSource oldSource = getTruckSourceByVehicleId(vehicleId);
            TruckSource truckSource = TruckSource.copyRelease(oldSource,param);
            truckSource.setVehicleId(vehicleId);
            truckSource.setTrackNo(vehicle.getTrackNo());
            truckSource.setCommTruckTypeId(vehicle.getCommTruckTypeId());
            truckSource.setCommTruckTypeName(vehicle.getCommTruckTypeName());
            truckSource.setTruckTypeName(vehicle.getTruckTypeName());
            truckSource.setOrganizeId(organize.getId());
            truckSource.setOrganizeName(organize.getOrganizeName());
            truckSource.setOrganizeLogo(organize.getOrganizeLogo());
            truckSource.setOrganizeMonthlyRating(organize.getMonthlyRating());
            truckSource.setOrganizeMemberTypeName(organize.getMemberTypeName());
            truckSource.setManageUserId(organize.getManagerUserId());
            if (truckSource.getSourceStatus()== TruckSource.SourceStatus.release){
                truckSource.setReleaseTime(new Date());
            }
            truckSource.setCreateTime(new Date());
            truckSource.setAddUserId(loginUser.getId());
            truckSourceMapper.insert(truckSource);
        }
    }

    @Override
    public TruckSource getTruckSourceByVehicleId(String vehicleId){
        QueryWrapper<TruckSource> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("vehicle_id",vehicleId);
        return truckSourceMapper.selectOne(queryWrapper);
    }

    //车辆详情链接
    private String getVehicleDetailUrl(String truckSourceId) {
        return String.format("%s/data/views/h5TruckSource?truckSourceId=%s",AppUtil.getZuulPath(),truckSourceId);
    }

    //操作标识
    private void ownerOptSet(TruckSource truckSource,Account loginUser){
        truckSource.setOwner(truckSource.getManageUserId().equals(loginUser.getId()));
        if (loginUser.getUserType() == UserType.shipperUser) {
            truckSource.setShipperCanPush(truckSource.getSourceStatus() == TruckSource.SourceStatus.release);
            truckSource.setOptTip("车源已上线，您可以点击底部按钮推送货源");
        }
        if (loginUser.getUserType() == UserType.truckerUser) {
            truckSource.setTruckerCanRelease(truckSource.getSourceStatus() != TruckSource.SourceStatus.release);
            truckSource.setTruckerCanScrap(truckSource.getSourceStatus() != TruckSource.SourceStatus.scrap);
            truckSource.setTruckerCanOffLine(truckSource.getSourceStatus() == TruckSource.SourceStatus.release);
            truckSource.setOptTip(truckSource.getSourceStatus().remark);
        }
    }

}
